package com.haoran.dwz.config;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

	@Value("${elasticsearch.cluster.hosts:localhost:9300,172.0.0.1:9300 }")
	private String[] hosts;

	@Value("${elasticsearch.cluster.key:cluster.name}")
	private String key;
	
	@Value("${elasticsearch.cluster.value:haoran}")
	private String value;

	/**
	 * @return
	 * @throws UnknownHostException
	 */
	@Bean
	public TransportClient transportClient() throws UnknownHostException {
		// TransportAddress 是 InetSocketAddress 包装类
		Builder builder = Settings.builder();
		Settings settings = builder.put(key, value).build();
		TransportClient client = new PreBuiltTransportClient(settings);
		for (int i = 0; i < hosts.length; i++) {
			String[] split = hosts[i].split(":");
			if(split != null && split.length == 2) {
				String ip = StringUtils.trim(split[0]);
				int port = Integer.parseInt(StringUtils.trim(split[1]));
				TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(ip), port);
				client.addTransportAddress(transportAddress);
			}
		}
		return client;
	}
}
